package ye.guo.huang.datatransferdemo.utils;

import java.security.MessageDigest;
import java.util.*;

public class SignUtils {
	public static String MD5Encrypt(Map<String, Object> dataMap, String secret) {
		String content = ASCIISort(dataMap, secret);
		String md5 = getMD5(content);
		return md5;
	}

	public static String getMD5(String content) {
		return getMD5(content, (Integer)null);
	}

	public static String getMD5(String content, Integer len) {
		MessageDigest md5 = null;

		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception var9) {
			System.out.println(var9.toString());
			var9.printStackTrace();
			return "";
		}

		char[] charArray = content.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for(int i = 0; i < charArray.length; ++i) {
			byteArray[i] = (byte)charArray[i];
		}

		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();

		for(int i = 0; i < md5Bytes.length; ++i) {
			int val = md5Bytes[i] & 255;
			if (val < 16) {
				hexValue.append("0");
			}

			hexValue.append(Integer.toHexString(val));
		}

		if (len != null && len != 16) {
			return hexValue.toString();
		} else {
			return hexValue.toString().substring(8, 24);
		}
	}

	public static String ASCIISort(Map<String, Object> dataMap, String secret) {
		String conetnt = "";
		if (dataMap.containsKey("sign")) {
			dataMap.remove("sign");
		}

		Collection<String> keyset = dataMap.keySet();
		List list = new ArrayList(keyset);
		Collections.sort(list);

		for(int i = 0; i < list.size(); ++i) {
			Object data = dataMap.get(list.get(i));
			if (!Objects.isNull(data)) {
				conetnt = conetnt + list.get(i) + "=" + dataMap.get(list.get(i)) + "&";
			}
		}

		if (secret != null) {
			conetnt = conetnt + "secret=" + secret;
		} else {
			conetnt = conetnt.substring(0, conetnt.length() - 1);
		}

		System.out.println("输出：" + conetnt);
		return conetnt;
	}
}

